package com.gzhryc.shared_device.oem.micro.queue.work;

import java.util.List;

import com.gzhryc.common.NumberTools;
import com.gzhryc.common.exceptions.LogicException;
import com.gzhryc.common.logging.Logger;
import com.gzhryc.shared_device.base.enums.EOperatorType;
import com.gzhryc.shared_device.base.models.OperateInfo;
import com.gzhryc.shared_device.oem.code.ConfigUtils;
import com.gzhryc.shared_device.oem.code.agent.dao.db.AgentRelationWallet;
import com.gzhryc.shared_device.oem.code.agent.dao.enums.AgentRelationWalletEnum;
import com.gzhryc.shared_device.oem.code.agent.services.AgentRelationWalletService;
import com.gzhryc.shared_device.oem.code.agent.services.dto.AgentRelationWalletSearch;
import com.gzhryc.shared_device.oem.code.config.BusinessConfig;
import com.gzhryc.shared_device.oem.micro.queue.MicroConstants;

public class AgentRelationWalletConvertWMRunnable implements Runnable{

    static Logger log = Logger.getLogger(AgentRelationWalletConvertWMRunnable.class);

    @Override
    public void run() {
        Integer pageNo = 1;
        Integer pageLimit = 100;

        OperateInfo operateInfo = new OperateInfo(MicroConstants.PROGRAM_TYPE, MicroConstants.PROGRAM_TYPE_NAME);
        operateInfo.setOperator(EOperatorType.System.index(), "凌晨1点定时检查程序");
        operateInfo.setOperateNote("每24小时转账至提现金额");

        AgentRelationWalletSearch search = new AgentRelationWalletSearch();
        search.setState(AgentRelationWalletEnum.State.Normal.index());
        BusinessConfig businessConfig = ConfigUtils.getBusinessConfig();
        List<AgentRelationWallet> agentRelationWalletList = AgentRelationWalletService.self().findBySearch(search,pageNo,pageLimit);
        while (agentRelationWalletList != null && agentRelationWalletList.size() > 0){
            for(AgentRelationWallet agentRelationWallet : agentRelationWalletList){
                if(agentRelationWallet.getMoney() > businessConfig.getReservedFund()){
                    Long money = agentRelationWallet.getMoney() - businessConfig.getReservedFund();
                    if(money > 0) {
	                    Double tempMoney = NumberTools.changeMoneyLi(money);
	                    Long withdrawalMoney = NumberTools.changeMoneyLi(Math.floor(tempMoney));
	                    try {
	                        AgentRelationWalletService.self().transferMoneyToWithdrawal(agentRelationWallet.getUserId(),agentRelationWallet.getRelationUserId()
	                                ,agentRelationWallet.getAccountGroupId(),withdrawalMoney,operateInfo);
	                    } catch (LogicException e) {
	                        log.error(e.getMessage(),e);
	                    }
                    }
                }
            }
            pageNo = pageNo + 1;
            agentRelationWalletList = AgentRelationWalletService.self().findBySearch(search,pageNo,pageLimit);
        }
    }
}
